package com.forum.module.blog.service.category;

import com.alibaba.nacos.shaded.com.google.common.annotations.VisibleForTesting;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.forum.framework.common.exception.util.ServiceExceptionUtils;
import com.forum.framework.common.pojo.PageResult;
import com.forum.framework.common.util.object.BeanUtils;
import com.forum.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.forum.module.blog.controller.category.vo.CategoryPageReqVO;
import com.forum.module.blog.controller.category.vo.CategorySaveReqVO;
import com.forum.module.blog.dal.dataobject.article.ArticleDO;
import com.forum.module.blog.dal.dataobject.category.CategoryDO;
import com.forum.module.blog.dal.mysql.category.CategoryMapper;
import org.springframework.stereotype.Service;

import static com.forum.module.system.enums.ErrorCodeConstants.CATEGORY_IS_EXISTS;
import static com.forum.module.system.enums.ErrorCodeConstants.CATEGORY_NOT_EXISTS;

/**
 * 功能:
 * 作者:ouyzh
 * 日期:2025/3/2 18:27
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, CategoryDO> implements CategoryService {
    private final CategoryMapper categoryMapper;

    public CategoryServiceImpl(CategoryMapper categoryMapper) {
        this.categoryMapper = categoryMapper;
    }

    @Override
    public Long createCategory(CategorySaveReqVO reqVO) {
        validUnique(reqVO);
        CategoryDO categoryDO = BeanUtils.toBean(reqVO, CategoryDO.class);
        Long sort = categoryMapper.selectCount();
        categoryDO.setSort(sort + 1);

        categoryMapper.insert(categoryDO);
        return categoryDO.getId();
    }

    @Override
    public void updateCategory(CategorySaveReqVO reqVO) {
        validUnique(reqVO);
        CategoryDO updateObj = BeanUtils.toBean(reqVO, CategoryDO.class);
        categoryMapper.updateById(updateObj);
    }

    private void validUnique(CategorySaveReqVO reqVO) {
        if (categoryMapper.exists(new LambdaQueryWrapperX<CategoryDO>().eqIfPresent(CategoryDO::getName, reqVO.getName()))) {
            throw ServiceExceptionUtils.exception(CATEGORY_IS_EXISTS);
        }
    }

    @Override
    public void deleteById(Long id) {
        // 1. 校验分类存在
        validateCategoryExists(id);

        categoryMapper.deleteById(id);
    }

    @Override
    public PageResult<CategoryDO> getCategoryPage(CategoryPageReqVO pageReqVO) {
        return categoryMapper.selectPage(pageReqVO);
    }

    @VisibleForTesting
    CategoryDO validateCategoryExists(Long id) {
        if (id == null) {
            return null;
        }
        CategoryDO categoryDO = categoryMapper.selectById(id);
        if (categoryDO == null) {
            throw ServiceExceptionUtils.exception(CATEGORY_NOT_EXISTS);
        }
        return categoryDO;
    }
}
